/**
 *HomeActivity.java
 *2011-9-18 �??10:00:06
 *Touch Android
 *http://bbs.droidstouch.com
 */
package org.buptsse.ui;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.message.BasicNameValuePair;
import org.buptsse.entity.Circle;
import org.buptsse.entity.MessageDetail;
import org.buptsse.entity.Post;
import org.buptsse.entity.ShortMessage;
import org.buptsse.entity.User;
import org.buptsse.thread.SendMessageThread;
import org.buptsse.utils.APPConstant;
import org.buptsse.utils.Action;
import org.buptsse.utils.ConnectionChecker;
import org.buptsse.utils.GloableInstance;
import org.buptsse.utils.HttpHelper;
import org.buptsse.utils.ImageService;
import org.buptsse.utils.JsonUtils;

import com.google.gson.reflect.TypeToken;

import android.R.integer;
import android.app.Activity;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class MessageActivity extends Activity implements OnScrollListener,OnClickListener{
	// Button footerButton;
	// LinearLayout footerProgressBarLayout;// 加载进度滚动条
	// View view;
	ListAdapter listAdapter = new ListAdapter();
	ListView list;
	int visibleItemCount;
	
	int scrollState;
	LinkedList<MessageDetail> messageList = new LinkedList<MessageDetail>();
	SharedPreferences preferences = null;

	Handler myHandler = new Handler() {
		public void handleMessage(Message msg) {
			if(pDialog!=null)
				pDialog.dismiss();
			switch (msg.what) {
			case APPConstant.NetUnavailable:
				Toast.makeText(getApplicationContext(), "网络连接不可用", 1000).show();
				break;
			case APPConstant.getMessageRecordsError:
				Toast.makeText(getApplicationContext(), "没有消息记录", 1000).show();
				break;
			case APPConstant.getMessageRecordsFinish:
				messageList=(LinkedList<MessageDetail>) msg.obj;
				listAdapter.count=messageList.size();
				//Toast.makeText(getApplicationContext(), "size:"+messageList.size(), 1000).show();
				listAdapter.notifyDataSetChanged();
				break;
			case APPConstant.sendMessageError:
				for(int i=messageList.size()-1;i>=0;i--)
				{
					if(messageList.get(i).getState().equals("正在发送"))
					{
						messageList.get(i).setState("发送失败");
					}else {
						break;
					}
				}
				listAdapter.count=messageList.size();
				listAdapter.notifyDataSetChanged();
				break;
			case APPConstant.sendMessageFinish:
				for(int i=messageList.size()-1;i>=0;i--)
				{
					if(messageList.get(i).getState().equals("正在发送"))
					{
						messageList.get(i).setState("");
					}else {
						break;
					}
				}
				listAdapter.count=messageList.size();
				listAdapter.notifyDataSetChanged();
				break;
			}
			super.handleMessage(msg);
		}
	};
	private int lastItem;
	private int count;
	private ProgressDialog pDialog;
	private ImageView senderPhotoImageView;
	private TextView senderNameTV;
	private Button backButton,sendButton;
	private String sender;
	private EditText messageET;

	public void showWaittingDialog(String msg)
	{
		pDialog=new ProgressDialog(this);
		pDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        pDialog.setMessage(msg); 
        pDialog.show(); 
	}
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Intent it = getIntent();
		ShortMessage msg=(ShortMessage) it.getSerializableExtra("message");
		sender=msg.getSender();
		setContentView(R.layout.message);
		listAdapter.count=0;
		list=(ListView) findViewById(R.id.message_list);
		//list.setDivider(new ColorDrawable(Color.parseColor("#ecf6eb")));
		//list.setDividerHeight(1);
		//list.setVerticalFadingEdgeEnabled(false);
		list.setAdapter(listAdapter);
		list.setOnScrollListener(this);
		
		messageET = (EditText)this.findViewById(R.id.sent_content);
		
		InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE); 
		imm.hideSoftInputFromWindow(messageET.getWindowToken(), 0);
		senderPhotoImageView=(ImageView) findViewById(R.id.sender_photo);
		senderPhotoImageView.setImageBitmap(ImageService.getImageByUrl(msg.getPhoto()));
		senderNameTV=(TextView) findViewById(R.id.sender_name);
		senderNameTV.setText(msg.getSender());
		backButton=(Button) findViewById(R.id.rd_back);
		backButton.setOnClickListener(this);
		sendButton=(Button) findViewById(R.id.rd_post);
		sendButton.setOnClickListener(this);
		GetMessageRecordsThread gmrt=new GetMessageRecordsThread(getApplicationContext(), myHandler, sender, GloableInstance.user.getName());
		gmrt.start();
		showWaittingDialog("正在加载消息记录");
	}

	private class GetMessageRecordsThread extends Thread {
		private Context context;
		private Handler handler;
		private String sender,receiver;
		
		public GetMessageRecordsThread(Context context,Handler handler,String sender,String receiver) {
			this.context=context;
			this.handler=handler;
			this.sender=sender;
			this.receiver=receiver;
		}
		@Override
		public void run() {
			if(ConnectionChecker.CheckConnection(context, handler)==false)
			{
				return;
			}
			ArrayList<NameValuePair> param=new ArrayList<NameValuePair>();
			param.add(new BasicNameValuePair("sender", sender));
			param.add(new BasicNameValuePair("receiver", receiver));
			try {
				String json=HttpHelper.sendPost(APPConstant.getMessageRecordsUrl, param);
				System.out.println("json is:"+json);
				if(json.equals("failure") || json.contains("failure"))
				{
					//失败
					Message msg=handler.obtainMessage(APPConstant.getMessageRecordsError);
					handler.sendMessage(msg);
					return;
				}else {
					//成功
					LinkedList<MessageDetail> list=(LinkedList<MessageDetail>) JsonUtils.getJsonObject(json, new TypeToken<LinkedList<MessageDetail>>() {}.getType());
					Message msg=handler.obtainMessage(APPConstant.getMessageRecordsFinish);
					msg.obj=list;
					handler.sendMessage(msg);
					return;
				}
			} catch (ClientProtocolException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	class ListAdapter extends BaseAdapter {
		int count = 10;
		@Override
		public int getCount() {
			return count;
		}
		@Override
		public Object getItem(int position) {
			return position;
		}
		@Override
		public long getItemId(int position) {
			return position;
		}
		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			LayoutInflater inflater = LayoutInflater.from(MessageActivity.this);
			View view = inflater.inflate(R.layout.listview_item_hot, null);
			LinearLayout layout = (LinearLayout)view.findViewById(R.id.main_linear_layout);
			TextView senderTextView=(TextView) view.findViewById(R.id.sender);
			TextView sendTimeTextView=(TextView) view.findViewById(R.id.send_time);
			TextView contentTextView=(TextView) view.findViewById(R.id.content);
			TextView stateTextView=(TextView) view.findViewById(R.id.state);
			MessageDetail messageDetail=messageList.get(position);
			senderTextView.setText(messageDetail.getSender());
			sendTimeTextView.setText(messageDetail.getTime());
			contentTextView.setText(messageDetail.getContent());
			if(messageDetail.getState()==null){
				stateTextView.setText("");
			}else {
				stateTextView.setText(messageDetail.getState());
			}
			if(messageDetail.getSender().equals(GloableInstance.user.getName()))
			{
				//自己发送的消息
				//layout.setBackgroundColor(R.drawable.bg_green);
				layout.setBackgroundResource(R.drawable.bg_green);
			}else
			{
				//别人发送的消息
				layout.setBackgroundResource(R.drawable.bg_hot);
			}
			return view;
		}
	}
	
	
	@Override
	public void onScroll(AbsListView view, int firstVisibleItem,
			int visibleItemCount, int totalItemCount) {
		this.visibleItemCount = visibleItemCount;
		lastItem = firstVisibleItem + visibleItemCount - 1;
		if (listAdapter.count >= count) {
			list.removeFooterView(view);
		}
	}

	@Override
	public void onScrollStateChanged(AbsListView view, int scrollState) {
		this.scrollState = scrollState;
	}

	@Override
	public void onClick(View v) {
		Intent it = new Intent();
		int vid=v.getId();
		System.out.println("click"+vid);
		switch(vid){
		case R.id.rd_back:
			//返回
			finish();
			break;
		case R.id.rd_post:
			//发送消息
			if(!messageET.getText().toString().equals(""))
			{
				String content=messageET.getText().toString();
				MessageDetail md=new MessageDetail();
				md.setContent(content);
				md.setSender(GloableInstance.user.getName());
				SimpleDateFormat sDateFormat=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");     
				String date=sDateFormat.format(new java.util.Date());
				md.setTime(date);
				md.setState("正在发送");
				messageList.add(md);
				listAdapter.count=messageList.size();
				listAdapter.notifyDataSetChanged();
				list.setSelection(list.getAdapter().getCount()-1); 
				messageET.setText("");
				SendMessageThread smt=new SendMessageThread(getApplicationContext(), myHandler, content, GloableInstance.user.getName(), sender,"false");
				smt.start();
			}
			break;
		}
	}

}
